#!/bin/bash
echo "This script is run manually after a backend channel scan"
echo "to repair channel numbers, call ids and xmltvids"
echo "It requires that channelscan.sh was run before the"
echo "backend scan (normally run every morning)."
set -e
. /etc/opt/mythtv/mythtv.conf
scriptname=`readlink -e "$0"`
scriptpath=`dirname "$scriptname"`

logfile=/var/log/mythtv/postscan.log

datetime=`date +%Y%m%d_%H%M`

debug=0
test=Y

echo $datetime Run Start >> $logfile

dumpfile=$DATADIR/${datetime}_channeldump.sql
sqlfile=$DATADIR/${datetime}_postscan.sql

if [[ "$test" != Y ]] ; then
    # Get DB password from /etc/mythtv/mysql.txt
    . /etc/mythtv/mysql.txt
    mysqlcmd="mysql --user=$DBUserName --password=$DBPassword --host=$SBHostname $DBName"
    rm -f $DATADIR/multiplex_post.csv $DATADIR/channel_post.csv
    echo "select mplexid, frequency, sourceid from dtv_multiplex;" | \
        $mysqlcmd  > $DATADIR/multiplex_post.csv
    echo "select chanid, channum, freqid, mplexid, serviceid, sourceid, callsign, name, xmltvid, recpriority, visible from channel;" | \
        $mysqlcmd > $DATADIR/channel_post.csv
    rm -f $sqlfile $dumpfile
    # Backup the channel table
    mysqldump --user=$DBUserName --password=$DBPassword --host=$SBHostname $DBName channel > $dumpfile
fi
awk -f $scriptpath/postscan.awk \
 debug=$debug sourceid=$DVB_SOURCEID \
 sqloutfile=$sqlfile \
 FS='\t' section=MULTIPLEX ver=1 $DATADIR/multiplex.csv \
 FS='\t' section=MULTIPLEX ver=2 $DATADIR/multiplex_post.csv \
 FS=' ' section=SCAN $DATADIR/scte65scan.out \
 FS='\t' section=CHANNEL ver=1 $DATADIR/channel.csv \
 FS='\t' section=CHANNEL ver=2 $DATADIR/channel_post.csv >> $logfile

while [[ true ]]; do
    if [[ -f $sqlfile ]] ; then
        echo Type yes to run the SQL, no to exit, or enter to view the SQL.
        read -e resp
        if [[ "$resp" = no || "$resp" = n ]]; then
            exit
        fi
    else
        echo "Everything is already correct. Nothing to do"
        exit
    fi
    if [[ "$resp" = yes ]]; then
        $mysqlcmd < $sqlfile
        exit
    fi
    if [[ "$resp" = "" ]]; then
        less $sqlfile
    fi
done
